#!/usr/bin/env python
# -*- encoding=utf-8 -*-

import logging
import logging.config
import os, sys
import codecs, string

reload(sys)
sys.setdefaultencoding('utf8')

if not os.path.isdir("log"):
    os.mkdir("log")
logging.config.fileConfig("logger.conf")
logger = logging.getLogger("copy_jenkins")


def istextfile(filename, blocksize = 512):
    tmp_obj = open(filename)
    contents = tmp_obj.read(blocksize)
    tmp_obj.close()
    text_characters = "".join(map(chr, range(32, 127)) + list("\n\r\t\b"))
    _null_trans = string.maketrans("", "")
    if '\0' in contents:
        return 0

    if not contents:
        return 1

    t = contents.translate(_null_trans, text_characters)
    if len(t)/len(contents) > 0.30:
        return 0
    return 1


def is_Binary_file(code_base_dir, changelistfile):
    binary_files = []
    with open(changelistfile) as changelist:
        filename = changelist.readline().rstrip('\r\n')
        while filename:
            full_path = os.path.join(code_base_dir, filename)
            # Skip '.tar' file for now upgrade this into only compare changed
            # files in the future.
            if ".tar" in str(full_path):
                print("{0} skipped due to tar file recognized.".format(full_path))
            elif os.path.isfile(full_path) and istextfile(full_path) == 0:
                binary_files.append(full_path)
            filename = changelist.readline().rstrip('\r\n')
    if len(binary_files) > 0:
        logger.error('It is Not Allowded to Upload Binary Files.')
        logger.error('BINARY_FILES: %s' % binary_files)
        return 1
    return 0


if __name__ == "__main__":
    if len(sys.argv) <= 2:
        print("please specify project dir and changefile list file")
        sys.exit(1)
    if not os.path.isfile(sys.argv[2]):
        print("changelist file {0} not exist".format(sys.argv[2]))
        sys.exit(1)
    work_dir = os.getcwd()
    os.chdir(work_dir)
    ret = is_Binary_file(sys.argv[1], sys.argv[2])
    if ret != 0:
        sys.exit(1)
    sys.exit(0)
